package bean;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sosr.serveur.IServeurRMI;
import sosr.serveur.ServeurRMI;


import base.Base;


public class Connexion {

	private String login;
	private String passwd;
	private String messages;



	private IServeurRMI srvRMI;

	static int port = 53000;

	public Connexion() {
		this.login = "";
		this.passwd = "";
		this.messages = "";
	}

	public Connexion(String login, String passwd) {
		this.login = login;
		this.passwd = passwd;
		this.messages = "";
	}

	
	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public void logout() {
		setLogin("");
		setPasswd("");
		setMessage("");
	}

	public boolean isConnect() {
		String pwd = "";
		boolean res = false;

		try {
			pwd = getEncodedPassword(passwd);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		if (login == null || passwd == null)
			return false;

		
		try {

			Registry reg = LocateRegistry.getRegistry(port);
			reg.lookup("serveurRMI");
			System.out.println("Connexion  \t\t\t\t\t\t\t\t\t\t[OK]");
			srvRMI = (IServeurRMI) reg.lookup("serveurRMI");

			srvRMI.open();

			res = srvRMI.identification(login, pwd);

			srvRMI.close();
			
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Connexion  \t\t\t\t\t\t\t\t\t\t[ECHEC]");
		}

		return res;

	}

	public void setMessage(String message) {
		this.messages = message;
	}

	public String getMessage() {
		return this.messages;
	}

	public boolean hasMessage() {
		if (this.messages.length() > 0)
			return true;
		else
			return false;
	}
	
	public IServeurRMI getSrvRMI() {
		return srvRMI;
	}

	private static String getEncodedPassword(String key) throws NoSuchAlgorithmException {
		
		byte[] uniqueKey = key.getBytes();
		byte[] hash = null;
		hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
		StringBuffer hashString = new StringBuffer();
		for (int i = 0; i < hash.length; ++i) {
			String hex = Integer.toHexString(hash[i]);
			if (hex.length() == 1) {
				hashString.append('0');
				hashString.append(hex.charAt(hex.length() - 1));
			} else {
				hashString.append(hex.substring(hex.length() - 2));
			}
		}
		return hashString.toString();
	}
}
